package com.cbl.v.ssczs.view.activity;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.http.SslError;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cbl.v.ssczs.R;
import com.cbl.v.ssczs.mode.entity.TDetail;
import com.cbl.v.ssczs.mode.util.NetStatusUtil;
import com.cbl.v.ssczs.view.agent.OnPageListener;
import com.mingle.widget.ShapeLoadingDialog;


public class KlsfForAllActivity extends com.cbl.v.ssczs.view.activity.BaseActivity {
    private WebView mWebView;
    private TextView mBtnShare;
    OnPageListener onPageListener;
    private ImageView title_back;
    private String webUrl;
    private SwipeRefreshLayout mSwipeRefresh;
    private LinearLayout mNoNetLayout;
    private TextView title_name;
    private ShapeLoadingDialog shapeLoadingDialog;
    private Toolbar toolBar;
    private TextView title_right;

    @Override
    protected int getLayout() {
        return R.layout.activity_webview_chart;
    }

    @Override
    public void initView() {
        hideTitleBar();
        shapeLoadingDialog = new ShapeLoadingDialog(getContext());
        initToolBar();
        mBtnShare = (TextView) findViewById(R.id.btn_share);

        mWebView = (WebView) findViewById(R.id.web);
        initWebView(mWebView);
        //        webUrl = "https://video.1398t.com/pk10/h5shipin/?app=1";
        webUrl = "http://m.500.com/info/index.php?c=zhongjiang&a=dlt&";
        //        webUrl = "https://m.qmcai.com/zixun/index.html";
        mWebView.loadUrl(webUrl);

        initRefresh();
    }

    private void initToolBar() {
        toolBar = (Toolbar) findViewById(R.id.toolbar);
        title_right = (TextView) findViewById(R.id.title_right);
        toolBar.setBackground(getResources().getDrawable(R.color.bg_red));
        title_name = (TextView) findViewById(R.id.title_name);
        title_name.setText("快乐十分-查询助手");

        //        setSupportActionBar(toolBar);
        //        ActionBar actionBar = getSupportActionBar();
        //        if (actionBar != null) {
        //            actionBar.setDisplayHomeAsUpEnabled(true);
        //            actionBar.setDisplayShowTitleEnabled(false);
        //        }
        toolBar.setTitle("");
        toolBar.setTitleTextColor(Color.WHITE);
    }


    private void initRefresh() {
        mNoNetLayout = (LinearLayout) findViewById(R.id.linearLayout_no_net);
        if (!NetStatusUtil.isConnected(this)) {
            mNoNetLayout.setVisibility(View.VISIBLE);
        } else {
            mNoNetLayout.setVisibility(View.GONE);
        }
        mSwipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh);
        //设置刷新时动画的颜色，可以设置4个
        mSwipeRefresh.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light,
                android.R.color.holo_orange_light, android.R.color.holo_green_light);
        mSwipeRefresh.setProgressViewOffset(false, 100, 200);
        mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!NetStatusUtil.isConnected(getContext())) {
                                    mNoNetLayout.setVisibility(View.VISIBLE);
                                    Toast.makeText(getContext(), "无网络", Toast.LENGTH_SHORT).show();
                                } else {
                                    mNoNetLayout.setVisibility(View.GONE);
                                    mWebView.reload();
                                }

                                mSwipeRefresh.setRefreshing(false);
                            }
                        });
                    }
                }).start();
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (mWebView != null) {
            mWebView.reload();
        }
    }

    @Override
    public void initData() {
        setOnPageListener(new OnPageListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
            }

            @Override
            public void onError() {
                mNoNetLayout.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void initListener() {

    }

    public void initWebView(WebView mWebView) {
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setSupportMultipleWindows(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSavePassword(false);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                //判断标题 title 中是否包含有“error”字段，如果包含“error”字段，则设置加载失败，显示加载失败的视图
                if (!TextUtils.isEmpty(title) && title.toLowerCase().contains("无法打开")) {
                    onPageListener.onError();
                }
            }
        });
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i("TAG", url);
                if (url == null) return false;
                if (url.substring(0, 17).equals("sslocal://webview")) {
                    try {
                        String str1 = url.substring(url.lastIndexOf("%") + 1, url.indexOf("&"));
                        view.loadUrl("https://i.snssdk.com/vertical/caipiao/detail/?caipiao_id=" + str1.substring(2,
                                str1.length()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                try {

                    if (url.startsWith("bytedance://") || url.startsWith("sslocal://")) {
                        if (url.equals(TDetail.SSQ)) {
                            title_name.setText("双色球");
                            view.loadUrl(TDetail.SSQ_URL);
                        }
                        if (url.equals(TDetail.DLT)) {
                            title_name.setText("大乐透");
                            view.loadUrl(TDetail.DLT_URL);
                        }
                        if (url.equals(TDetail.FC3D)) {
                            title_name.setText("福彩3D");
                            view.loadUrl(TDetail.FC3D_URL);
                        }
                        if (url.equals(TDetail.PL3)) {
                            title_name.setText("排列三");
                            view.loadUrl(TDetail.PL3_URL);
                        }
                        if (url.equals(TDetail.PL5)) {
                            title_name.setText("排列五");
                            view.loadUrl(TDetail.PL5_URL);
                        }
                        if (url.equals(TDetail.QXC)) {
                            title_name.setText("七星彩");
                            view.loadUrl(TDetail.QXC_URL);
                        }
                        if (url.equals(TDetail.QLC)) {
                            title_name.setText("七乐彩");
                            view.loadUrl(TDetail.QLC_URL);
                        }
                        if (url.equals(TDetail.BQC)) {
                            title_name.setText("6场半全场");
                            view.loadUrl(TDetail.BQC_URL);
                        }
                        if (url.equals(TDetail.SFC)) {
                            title_name.setText("胜负彩");
                            view.loadUrl(TDetail.SFC_URL);
                        }
                        if (url.equals(TDetail.JQC)) {
                            title_name.setText("4场进球彩");
                            view.loadUrl(TDetail.JQC_URL);
                        }
                        return true;
                    }
                } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }


                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                shapeLoadingDialog.setLoadingText("加载中...");
                shapeLoadingDialog.show();

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                onPageListener.onError();
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
    }

    public void setOnPageListener(OnPageListener onPageListener) {
        this.onPageListener = onPageListener;
    }

    private long lastBackPress;

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }
}
